package cn.edu.tju.elm.controller;

import cn.edu.tju.elm.service.ProductService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.edu.tju.core.model.Product;
import cn.edu.tju.core.utils.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping
    public HttpResult create(@RequestBody Product product) {
        boolean saved = productService.save(product);
        return saved ? HttpResult.ok(product) : HttpResult.fail("创建失败");
    }

    @PutMapping("/{id}")
    public HttpResult update(@PathVariable Integer id, @RequestBody Product product) {
        product.setId(id);
        boolean updated = productService.updateById(product);
        return updated ? HttpResult.ok(product) : HttpResult.fail("更新失败");
    }

    @DeleteMapping("/{id}")
    public HttpResult delete(@PathVariable Integer id) {
        boolean removed = productService.removeById(id);
        return removed ? HttpResult.ok(true) : HttpResult.fail("删除失败");
    }

    @GetMapping("/{id}")
    public HttpResult get(@PathVariable Integer id) {
        Product product = productService.getById(id);
        return product != null ? HttpResult.ok(product) : HttpResult.fail("商品不存在");
    }

    @GetMapping("/list")
    public HttpResult list(@RequestParam(required = false) String name,
                       @RequestParam(required = false) Integer merchantId,
                       @RequestParam(required = false) BigDecimal minPrice,
                       @RequestParam(required = false) BigDecimal maxPrice,
                       @RequestParam(defaultValue = "1") long page,
                       @RequestParam(defaultValue = "10") long size) {
        QueryWrapper<Product> qw = new QueryWrapper<>();
        if (name != null && name.trim().length() > 0) {
            qw.like("name", name.trim());
        }
        if (merchantId != null) {
            qw.eq("merchant_id", merchantId);
        }
        if (minPrice != null) {
            qw.ge("price", minPrice);
        }
        if (maxPrice != null) {
            qw.le("price", maxPrice);
        }
        Page<Product> p = productService.page(new Page<>(page, size), qw);
        return HttpResult.ok(p);
    }

    @GetMapping("/merchant/{merchantId}")
    public HttpResult getByMerchantId(@PathVariable Integer merchantId) {
        List<Product> products = productService.getProductsByMerchantId(merchantId);
        return HttpResult.ok(products);
    }
}
